import request from './http'
import { v1 } from 'uuid'
import CryptoJS from 'crypto-js'
import { checkPermission } from '@/utils/directive'
import { getDefaultWhiteList, FilterXSS } from 'xss'
import { busConfigStore } from '@/afterSales/views/config/serviceConfig/store/busConfigStore'
// 上传文件限制类型
export const UPLOAD_LIMITED_TYPE = ['js', 'jsp', 'html', 'php', 'asp', 'aspx', 'jspx', 'exe', 'sh', 'py', 'vbs', 'xml', 'htm']
export function formRollToFirstError (paneNode, revise = 0) { // 表单校验有问题时，滚动到第一个el-error的位置
  setTimeout(() => { // 延时是为了解决偶发异步取不到is-error节点
    const pane = paneNode.getElementsByClassName('is-error')[0]
    if (pane) {
      paneNode.scrollTop = pane.offsetTop + revise
      const textareaNode = pane.getElementsByClassName('el-textarea__inner') // 多行文本
      const inputNode = pane.getElementsByClassName('el-input__inner') // 单行文本，日期，日期时间，下拉框，数字等
      if (textareaNode && textareaNode[0]) {
        textareaNode[0].focus()
      } else if (inputNode && inputNode[0]) {
        inputNode[0].focus()
      }
    }
  }, 100)
}
export function handleData (list, type) {
  const obj = {}
  busConfigStore[type + 'List'] = []
  list.map(item => {
    busConfigStore[type + 'List'].push({
      id: item.id,
      name: item.name
    })
    obj[item.id] = {
      members: item.members || [],
      name: item.name,
      id: item.id
    }
  })
  busConfigStore[type + 'Map'] = obj
}
export const commonAction = (actionObj: any) => {
  return request({
    url: actionObj.url,
    method: actionObj.method,
    params: actionObj.data,
    data: actionObj.data,
    hideLoading: actionObj.hideLoading
  })
}
export function uuid () {
  return v1().replace(/-/g, '')
}
export const filterXSS = (() => {
  const whiteList: any = getDefaultWhiteList() // 获取默认白名单
  // 添加新的白名单标签或属性
  for (const i of Object.keys(whiteList)) {
    whiteList[i].push('style', 'class')
    if (i === 'table' && whiteList[i]) {
      whiteList[i].push('cellpadding', 'cellspacing', 'bordercolor')
    }
  }
  whiteList.strike = ['style', 'class']
  const options = {
    whiteList,
    css: false,
    stripIgnoreTag: true, // 非白名单标签，过滤标签，显示标签里的内容
    stripIgnoreTagBody: ['script', 'style']
  }
  const myxss = new FilterXSS(options)
  return myxss.process.bind(myxss)
})()
export const deepClone = (targetObj: any) => {
  let tempObj: any
  if (typeof targetObj === 'object') {
    if (targetObj === null) {
      tempObj = null
    } else {
      if (targetObj instanceof Date) {
        tempObj = targetObj
      } else if (targetObj instanceof Array) {
        tempObj = []
        for (let i = 0, len = targetObj.length; i < len; i++) {
          tempObj.push(deepClone(targetObj[i]))
        }
      } else {
        tempObj = {}
        for (const j in targetObj) {
          tempObj[j] = deepClone(targetObj[j])
        }
      }
    }
  } else {
    tempObj = targetObj
  }
  return tempObj
}
// 获取当前时间
export function getCurrentDateTime () {
  const date = new Date()
  const year = date.getFullYear()
  let month: any = date.getMonth()
  let day: any = date.getDate()
  let h: any = date.getHours()
  let m: any = date.getMinutes()
  let s: any = date.getSeconds()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  h = h > 9 ? h : '0' + h
  m = m > 9 ? m : '0' + m
  s = s > 9 ? s : '0' + s
  return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
}
/**
 * (86401, true) -->  1天0小时0分1秒
 * (86401, false) -->  24:00:01
 */
export const getCallTimeLength = (second: any, format: any) => {
  if (second) {
    let h: any
    let m: any
    let s: any
    if (second === null || second < 0) {
      return
    }
    const d = Math.floor(second / (24 * 3600 * 1000))
    h = second / 3600 | 0
    second = parseFloat(second) - h * 3600
    if (parseInt(h, 16) < 10) {
      h = '0' + h
    }
    m = second / 60 | 0
    s = (parseFloat(second) - m * 60).toFixed(0)
    if (parseInt(m, 16) < 10) {
      m = '0' + m
    }
    if (s < 10) {
      s = '0' + s
    }
    if (format) {
      let time: string = ''
      if (d > 0) {
        time += d + '天'
      }
      if (h > 0) {
        time += h + '时'
      }
      if (m > 0) {
        time += m + '分'
      }
      if (s > 0) {
        time += s + '秒'
      }
      return time
    } else {
      return h + ':' + m + ':' + s
    }
  } else {
    return '00:00:00'
  }
}
/**
 * (type: noYear) -->  23:23:34
 * (type: '') -->  2020-10-23 23:23:34
 */
export function getFormatDateTime (date: any, type: string) {
  if (typeof date === 'string') {
    date = new Date(date)
  }
  const year = date.getFullYear()
  let month = date.getMonth()
  let day = date.getDate()
  let hour = date.getHours()
  let minites = date.getMinutes()
  let second = date.getSeconds()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  hour = hour > 9 ? hour : '0' + hour
  minites = minites > 9 ? minites : '0' + minites
  second = second > 9 ? second : '0' + second
  if (type === 'noYear') {
    return hour + ':' + minites + ':' + second
  } else {
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minites + ':' + second
  }
}
/**
 * (type: noTime) -->  07月23日
 * (type: '') -->  07月23日11:20
 * 跨年份 --> 加上年
 */
export function timeFormat (value, type) {
  const now = new Date()
  const today = now.setHours(0, 0, 0, 0)
  const yestoday = new Date(today - 24 * 60 * 60 * 1000).setHours(0, 0, 0, 0)
  const years = now.getFullYear()
  if (value) {
    const dataTimeArr = value.split(' ')
    const day = dataTimeArr[0].split('-')
    day[1] = Number(day[1])
    day[2] = Number(day[2])
    const dayTimeArr = dataTimeArr[1].split(':')
    const dayTime = `${dayTimeArr[0]}:${dayTimeArr[1]}`
    const valueDate = new Date(value)
    const currentDay = valueDate.setHours(0, 0, 0, 0)
    const currentYear = valueDate.getFullYear()
    let time = ''
    if (today === currentDay) {
      time = '今天' + ' ' + dayTime
    } else if (yestoday === currentDay) {
      time = '昨天' + ' ' + dayTime
    } else if (currentYear === years) {
      if (type === 'noTime') {
        time = `${day[1]}月${day[2]}日`
      } else {
        time = `${day[1]}月${day[2]}日 ${dayTime}`
      }
    } else {
      if (type === 'noTime') {
        time = `${day[0].substr(2)}年${day[1]}月${day[2]}日`
      } else {
        time = `${day[0].substr(2)}年${day[1]}月${day[2]}日 ${dayTime}`
      }
    }
    return time
  }
}

export const formatStamp = (tiemStamp: any) => {
  const time = new Date(tiemStamp)
  const y = time.getFullYear()
  let m: any = time.getMonth()
  let d: any = time.getDate()
  let h: any = time.getHours()
  let mm: any = time.getMinutes()
  let s: any = time.getSeconds()
  m = m + 1 > 9 ? m + 1 : '0' + (m + 1)
  d = d > 9 ? d : '0' + d
  h = h > 9 ? h : '0' + h
  mm = mm > 9 ? mm : '0' + mm
  s = s > 9 ? s : '0' + s
  return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s
}

export const regexPass = (passwordNew: string, temporary: string) => {
  let regex = false
  const lengthRegex = new RegExp('^.{8,}$') // >= 8位
  const characterRegex = new RegExp('[a-z]') // 小寫
  const characterRegex2 = new RegExp('[A-Z]') // 大寫
  const numberRegex = new RegExp('[0-9]')// 數字
  const chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
  let num = 0
  temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
  if (characterRegex.test(passwordNew)) {
    num += 1
  }
  if (characterRegex2.test(passwordNew)) {
    num += 1
  }
  if (numberRegex.test(passwordNew)) {
    num += 1
  }
  if ((passwordNew.length - temporary.length) > 0) {
    num += 1
  }
  if (num >= 3) {
    regex = true
  } else {
    regex = false
  }
  if (!lengthRegex.test(passwordNew)) {
    regex = false
  }
  if (chinese.test(passwordNew)) {
    regex = false
  }
  const limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
  for (let i = 0; i < limitArr.length; i++) {
    if (passwordNew.indexOf(limitArr[i]) > -1) {
      regex = false
      break
    }
  }
  return regex
}
export const storageManager = {
  set (key: string, value: string) {
    try {
      window.localStorage.setItem(key, value)
    } catch (e) {
      console.error(e)
    }
  },
  get (key: string) {
    return window.localStorage[key]
  }
}
export const isHasFuncOrMenus = (key: string, user: any, type: boolean) => { // 获取当前座席的权限（菜单权限和应用权限）
  const arr = type ? user.limits : user.functions // type ? 取菜单权限 : 取应用权限
  if (arr.indexOf(key) > -1) {
    return true
  } else {
    return false
  }
}

export const getCallStatusName = (status: string) => {
  let label = '--'
  switch (status) {
    case 'IVR':
      label = 'IVR'
      break;
    case 'QUEUE_ABANDON':
      label = '排队放弃'
      break;
    case 'RING':
      label = '预览外呼'
      break;
    case 'ANSWER':
      label = '已接听'
      break;
    case 'AGENT_NO_ANSWER':
      label = '座席未接听'
      break;
    case 'CALL_LIMITE':
      label = '并发限制'
      break;
    case 'BLACK_LIST':
      label = '黑名单'
      break;
    case 'CUSTOMER_NO_ANSWER':
      label = '客户未接听'
      break;
    case 'CALL_TRANSFER':
      label = '呼叫转移'
      break;
    case 'CALL_CONSULT':
      label = '呼叫咨询'
      break;
    case 'CALL_CONSULT_TRANSFER':
      label = '咨询转移'
      break;
    case 'CALL_THREEWAY':
      label = '三方'
      break;
    case 'VOICEMAIL':
      label = '留言'
      break;
    case 'RISK':
      label = '风控拦截'
      break;
  }
  return label
}
export const getCallTypeName = (type: string) => {
  let label = '--'
  switch (type) {
    case 'incoming':
      label = '呼入'
      break;
    case 'dialout':
      label = '外呼'
      break;
    case 'transfer':
      label = '转移'
      break;
    case 'consultTransfer':
      label = '咨询转移'
      break;
    case 'webcall':
      label = '双向回呼'
      break;
    case 'previewDialout':
      label = '预览外呼'
      break;
    case 'autoDialout':
      label = '自动外呼'
      break;
  }
  return label
}
export function millsToDate (mills: number) {
  if (mills < 0) {
    return '00:00:00'
  }
  // 计算出相差天数
  const days = Math.floor(mills / (24 * 3600 * 1000))
  // 计算出小时数
  const leave1 = mills % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
  const hours = Math.floor(leave1 / (3600 * 1000))
  // 计算相差分钟数
  const leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
  const minutes = Math.floor(leave2 / (60 * 1000))
  // 计算相差秒数
  const leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
  const seconds = Math.round(leave3 / 1000)
  let str = ''
  let hoursOne: any = ''
  let minutesOne: any = ''
  let secondsOne: any = ''
  if (days !== 0) {
    hoursOne = days * 24 + hours
  } else {
    hoursOne = (hours === 0) ? '00' : (hours >= 10 ? hours : ('0' + hours))
  }
  minutesOne = (minutes === 0) ? '00' : (minutes >= 10 ? minutes : ('0' + minutes))
  secondsOne = (seconds === 0) ? '00' : (seconds >= 10 ? seconds : ('0' + seconds))
  str = hoursOne + ':' + minutesOne + ':' + secondsOne
  return str
}

/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag 是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
*/
export function randomWord (min: number) {
  let str = ''
  const range = min
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  for (let i = 0; i < range; i++) {
    const pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

/**
 * 判断数据类型
 * @param data: any 要判断的数据
 * @returns typeof string 如：Object、Array、Boolean、String、Function、Undefined、Null
 */
export function toRawType (value: any) {
  return Object.prototype.toString.call(value).slice(8, -1);
}

/**
 * 获取小铃铛消息的跳转路径
 * @param msgKey 消息的KEY
 * @returns routerPath
 */
export function getBellMessagePath (type: string, msgKey: string, transTaskType: string) {
  if (!msgKey || msgKey.indexOf('V7') < -1) {
    console.error('可能不是本系统的消息，跳转失败');
    return false
  }
  console.log(type)
  const pathKey = (msgKey.split('__') || ['', ''])[1]
  if (!pathKey) {
    return false
  }
  const pathObj = {
    TX_CALLSHEET: 'cdr', // 通话记录
    TX_RECORD: 'cdrRecordFile', // 通话录音
    TX_PREVIEW_DIALOUT: 'previewDialout', // 预览外呼
    TX_AUTO_CALL_TASK: 'autoCallTask', // 自动外呼
    TX_CHAT_SESSION: 'chatSession', // 会话记录
    TX_CHAT_SESSION_CONTENT: 'chatSessionContent', // 会话内容
    TX_LEAVE_SESSION: 'leaveSession', // 留言记录
    TX_SIP: 'sip', // 号码管理
    TX_AGENT: 'agent', // 座席导入
    TX_KM: 'km', // 知识库
    TX_SESSION_TAG: 'sessionTags', // 会话标签
    TX_DEPARTMENT: 'department',
    SMS: 'sms'
  }
  const taskModule = pathObj[pathKey]
  switch (type) {
    case 'transmit': // 传输中心
      return taskModule ? `/transmission_center/index/${transTaskType || ''}?taskModule=${taskModule}` : `/transmission_center/index/${transTaskType || ''}`
  }
  if (!taskModule) {
    return ''
  }
  return ''
}

// 处理标签树形结构
export function handleLabelData (data: any, newObj?: any, str?: any, color?: string) {
  for (let i = 0; i < data.length; i++) {
    let newStr = str
    if (newStr) {
      newStr += '/' + data[i].name
    } else {
      newStr = data[i].name
    }
    const newColor = color || data[i].color
    data[i].name = newStr
    newObj[data[i]._id] = { name: data[i].name, color: color || data[i].color, _id: data[i]._id }
    const options = deepClone(data[i].children)
    if (options && options.length > 0) {
      handleLabelData(options, newObj, newStr, newColor)
    }
  }
  return newObj
}

export function encrypt (str, secretKey) {
  const key = CryptoJS.enc.Utf8.parse(secretKey)
  const srcs = CryptoJS.enc.Utf8.parse(str)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

export function decrypt (str, secretKey) {
  const key = CryptoJS.enc.Utf8.parse(secretKey)
  const decryptStr = CryptoJS.AES.decrypt(str, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decryptStr).toString()
}

export function _encryptPhone (phone) {
  if (!phone) {
    return ''
  }
  const len = phone.length
  if (len < 6) {
    return phone
  }
  let tel = ''
  const mobile = /1[3,4,5,7,8][0-9]{9}/
  if (mobile.test(phone)) {
    tel = phone.substring(0, 3) + '****' + phone.substring(7)
  } else {
    const p = len / 2
    tel = phone.substring(0, p - 2) + '****' + phone.substring(p + 2)
  }
  return tel
}

// 隐藏号码
export function checkHideTel (phone: string) {
  if (!phone) {
    return ''
  }
  if (checkPermission(null, { value: ['other_hide_number'] }, 'limits')) {
    return _encryptPhone(phone)
  } else {
    return phone
  }
}
